import Permissions from "react-native-permissions";
import { Alert } from "react-native";
import ImagePicker from "react-native-image-picker";
import { isIOS } from "../common";

const options = {
  title: "选择图片",
  cancelButtonTitle: "取消",
  takePhotoButtonTitle: "拍照",
  chooseFromLibraryButtonTitle: "手机相册",
  maxHeight: 720, // 720
  maxWidth: 480, // 480
  permissionDenied: {
    title: "权限请求失败",
    text: "请在设置中打开“相机”和“手机存储”权限",
    reTryTitle: "重试",
    okTitle: "确定",
  },
  storageOptions: {
    skipBackup: true,
    cameraRoll: false,
  },
};

const DEFAULT_SOURCE = require("../img/ic_default_pic.png");

export default class MyImgPicker {
  static defaultSource = DEFAULT_SOURCE;
  static justShowWithDefaultSource = true;

  static init(defaultSource, justShowWithDefaultSource) {
    this.defaultSource = defaultSource;
    this.justShowWithDefaultSource = justShowWithDefaultSource;
  }

  static _showIOSImagePicker() {
    return new Promise((resolve, reject) => {
      Permissions.checkMultiple(["camera", "photo"]).then(response => {
        if (response.camera === "denied" || response.photo === "denied") {
          Alert.alert("提示", "请先打开你的相册和相机访问权限，才能正常上传", [
            {
              text: "不允许",
              onPress: () => console.log("Permission denied"),
              style: "cancel",
            },
            { text: "去设置", onPress: Permissions.openSettings },
          ]);
          reject();
        } else {
          this._showImagePicker()
            .then(uriObj => resolve(uriObj))
            .catch(() => reject());
        }
      });
    });
  }

  static _showImagePicker() {
    return new Promise((resolve, reject) => {
      ImagePicker.showImagePicker(options, response => {
        console.log("Response = ", response);

        if (response.didCancel) {
          console.log("User cancelled image picker");
          reject();
        } else if (response.error) {
          console.log("ImagePicker Error: ", response.error);
          reject();
        } else if (response.customButton) {
          console.log("User tapped custom button: ", response.customButton);
          reject();
        } else {
          resolve({ uri: response.uri });
        }
      });
    });
  }

  static showImgPicker() {
    return new Promise((resolve, reject) => {
      if (isIOS) {
        this._showIOSImagePicker()
          .then(uriObj => resolve(uriObj))
          .catch(() => reject());
      } else {
        this._showImagePicker()
          .then(uriObj => resolve(uriObj))
          .catch(() => reject());
      }
    });
  }
}
